package org.phoenix.mall.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.phoenix.mall.admin.common.pojo.vo.UserVO;
import org.phoenix.mall.admin.common.utils.PagedGridResult;
import org.phoenix.mall.admin.mapper.GoodsMapper;
import org.phoenix.mall.admin.pojo.Goods;
import org.phoenix.mall.admin.service.GoodsService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Override
    public int add(Goods goods) {
        return goodsMapper.insert(goods);
    }

    @Override
    public PagedGridResult getGoodsListByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Goods> list = goodsMapper.selectAll();

        if (CollectionUtils.isEmpty(list)){
            page = page - 1;
            page = page < 1 ? 1 : page;

            PageHelper.startPage(page, pageSize);
            list = goodsMapper.selectAll();
        }

        return setterPagedGrid(list, page);
    }

    private PagedGridResult setterPagedGrid(List<Goods> list, Integer page) {
        PageInfo<Goods> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }
}
